package com.html2rss.core.parser;

import org.apache.commons.jxpath.JXPathContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import java.io.*;

import com.dappit.Dapper.parser.EnviromentController;
import com.dappit.Dapper.parser.MozillaParser;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

/**
 * User: vvs
 * Date: 01.04.2007
 * Time: 19:06:55
 */
public class HTMLFeedExtracter {
    public static class Bean {
        int a;

        public int getA() {
            return a;
        }

        public void setA(int a) {
            this.a = a;
        }
    }

    public static String saveXMLDocumentToString(Node doc) {
// open output stream where XML Document will be saved
        Writer fos  = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            fos = new OutputStreamWriter(baos, "windows-1251");
        } catch (UnsupportedEncodingException e) {}
        Transformer transformer;
// Use a Transformer for output
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        try {
            transformer = transformerFactory.newTransformer();
        }
        catch (TransformerConfigurationException e) {
            System.out.println("Transformer configuration error: " + e.getMessage());
            return null;
        }
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(fos);
        // transform source into result will do save
        try {
            transformer.transform(source, result);
        }
        catch (TransformerException e) {
            System.out.println("Error transform: " + e.getMessage());
        }
        System.out.println("XML file saved.");
        return baos.toString();
    }

    public static boolean saveXMLDocument(String fileName, Document doc) {
        System.out.println("Saving XML file... " + fileName);
// open output stream where XML Document will be saved
        File xmlOutputFile = new File(fileName);
        FileWriter fos;
        Transformer transformer;
        try {
            fos = new FileWriter(xmlOutputFile);
            fos.write(saveXMLDocumentToString(doc));
            fos.close();
        }
        catch (FileNotFoundException e) {
            System.out.println("Error occured: " + e.getMessage());
            return false;
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return true;
    }

    public HTMLFeedExtracter(String url, String[] nodePath) throws Exception {
        MozillaParser parser = new MozillaParser();
        Document doc = parser.parse(HtmlToRss.readFile(url));
        saveXMLDocument("testout.xml", doc);
        String[][] paths = splitStrings(nodePath);

//        int k = getCommonPrefixLength(paths);


        Node node = doc.getChildNodes().item(0);
        JXPathContext context = JXPathContext.newContext(doc);
        System.out.println(context.getValue("*"));

    }

    public static void initParser(String mozillaLibraryBaseDirectory) throws Exception {
        File parserLibraryFile = new File(mozillaLibraryBaseDirectory+"/native/bin/MozillaParser" + EnviromentController.getSharedLibraryExtension());
        String parserLibrary = parserLibraryFile.getAbsolutePath();
        System.out.println("Loading Parser Library :" + parserLibrary);
        //	mozilla.dist.bin directory :
        final File mozillaDistBinDirectory = new File(mozillaLibraryBaseDirectory+ "/mozilla.dist.bin." + EnviromentController.getOperatingSystemName());
        MozillaParser.init(parserLibrary, mozillaDistBinDirectory.getAbsolutePath());
    }

    private String[][] splitStrings(String[] nodePath) {
        String[][] paths = new String[nodePath.length][];
        for (int i = 0; i < paths.length; i++) {
            paths[i] = nodePath[i].split(" ");
        }
        return paths;
    }

    private int getCommonPrefixLength(String[][] paths) {
        int k = 0;
        while (true) {
            boolean eq = true;
            for (int i = 1; i < paths.length; i++) {
                if (paths[k][i] != paths[k][i - 1]) eq = false;
            }
            if (!eq) break;
        }
        return k;
    }

    public static void main(String[] args) throws Exception {
        new HTMLFeedExtracter("out.html", new String[]{"HTML[0] BODY[1] P[4]"});
    }
}
